###
import pandas as pd
from pathlib import Path
import json
from geopy.geocoders import Nominatim

class DatasetSplit(object):
    '''
    划分训练集，验证集的方法
    '''
    def __init__(self,df):
        self.df = df
    def straight_split(self):
        '''
        直接分：
        '''
        pass

class DataVisualize(object):
    '''
    封装一些可视化数据分析的功能
    '''
    def __init__(self):
        pass

def map_county_2_lonlat():
    pd.set_option('display.max_columns', 500)
    files = list(Path("data/").glob("*.csv"))
    for file in files:
        print(f"creates: '{file.stem}'")
        globals()[file.stem] = pd.read_csv(file)
    f = open('data/county_id_to_name_map.json')
    name_mapping = {
        "valga": "valg",
        "põlva": "põlv",
        "jõgeva": "jõgev",
        "rapla": "rapl",
        "järva": "järv"
    }

    county_codes = json.load(f)

    parsed_counties = {v.lower().rstrip("maa"): k for k, v in county_codes.items()}
    parsed_counties_clean = {name_mapping.get(k, k): v for k, v in parsed_counties.items()}
    county_data = {v: [] for _, v in parsed_counties_clean.items()}

    forecast_weather = pd.read_csv('data/forecast_weather.csv')
    for i, coords in forecast_weather[["latitude", "longitude"]].drop_duplicates().iterrows():

        lat, lon = coords["latitude"], coords["longitude"]

        geoLoc = Nominatim(user_agent="GetLoc") # 一个自动查询经纬度的库

        # passing the coordinates
        locname = geoLoc.reverse(f"{lat}, {lon}")  # lat, lon
        if locname is None: continue

        location = locname.raw["address"]
        if location["country"] == "Eesti": # 限制了国家 -> 比赛页面有说明国家Estonian
            county = location['county'].split()[0].lower()
            county = name_mapping.get(county, county)
            print(f"county: '{county}', county code:", parsed_counties_clean[county], (lat, lon))
            county_data[parsed_counties_clean[county]].append((lat, lon))
    # 存入表格：
    df_data = {"county": [], "longitude": [], "latitude": []}
    for k, v in county_data.items():
        df_data["county"] += [k] * len(v)
        df_data["latitude"] += [x[0] for x in v]
        df_data["longitude"] += [x[1] for x in v]
    pd.DataFrame(df_data).to_csv("/kaggle/working/county_lon_lats.csv")

if __name__ == '__main__':
    map_county_2_lonlat()





